//获取小说接口
'use strict';
let uniId = require('uni-id')
let db = uniCloud.database()
let dbCommad = db.command
exports.main = async (event, context) => {
	//处理url化的post接口,如果你的接口无需暴露接口给别人用就无需关心下面的代码
	if(event.body){
		let ip =event.headers['x-real-ip']
		event={
			...JSON.parse(event.body)
		},
		//这里需要手动传入context参数
		uniId = uniId.createInstance({ // 创建uni-id实例，其上方法同uniID
		    context:{
				PLATFORM:'app-plus',
				APPID:'__UNI__B10F710',
				LOCALE:'zh-Hans',
				CLIENTIP:ip
			}, // 传入context防止不同请求互相影响
		})
	}
	//end 处理url化
	
	//校验token
	let result = await payloadToken(event)
	if (result.code != 0) { //校验不成功【如果校验成功返回uid】
		return result
	}

	let res = {}
	//保存或更新已经上传的文件
	if (event.active == 'uploadFile') {
		res = await setUploadFile(event)
	}
	//删除云存储中无用数据和数据库文件数据
	if (event.active == 'delectFile') {
		res = await delectFile(event)
	}
	if (event.active == 'delectFile') {
		res = await delectFile(event)
	}
	// 返回数据给客户端
	return res
};
//删除无用文件
async function delectFile(event){
	let data =await db.collection('fileList').where({
		isUse:false
	}).field({
		fileId:true,
		_id:false
	}).get()
	let fileList=data.data.map(item=>item.fileId)
	let del = await uniCloud.deleteFile({ fileList});
	console.log(del);
	if(del.length>0){
		await db.collection('fileList').where({isUse:false}).remove()
	}
	let result = {
		code: 0,
		data:del,
		msg: '成功'
	}
	return result
}
//保存已经上传的文件
async function setUploadFile(event){
	let result = {}
	if(event.params&&event.params.type){
		if(event.params.type=='add'){
			let data=await db.collection('fileList').add({
				fileId:event.params.fileId,
				isUse:false//是否被使用
			})
			result = {
				code: 0,
				data,
				msg: '成功'
			}
		}else if(event.params.type=='update'){
			let data=await db.collection('fileList').where({fileId:event.params.fileId}).update({
				isUse:true//是否被使用
			})
			result = {
				code: 0,
				data,
				msg: '成功'
			}
		}
	}else {
		result = {
			code: 400,
			msg: '参数错误'
		}
	}
	return result
}
//校验token
async function payloadToken(event) {
	//校验token
	let payload = {}
	//用户带的参数
	let params = event.params || {}
	if (!event.token) {
		return {
			code: 403,
			msg: '用户未登录或登录失效'
		}
	}
	//校验token
	payload = await uniId.checkToken(event.token);
	//校验失败
	if (payload.code && payload.code > 0) {
		return payload
	}
	params.uid = payload.uid //校验成功之后会返回用户Id
	return {
		code: 0,
		...params
	}
}
